﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 添加采购/委外订单
    /// </summary>
    public class CreatePurchaseOutsourceHandler : IRequestHandler<CreatePurchaseOutsourceCommand, Result>
    {
        /// <summary>
        /// 采购/委外订单仓储
        /// </summary>
        private readonly IBaseRepository<PurchaseOutsources> _purchaseOutsourceRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreatePurchaseOutsourceHandler> _logger;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="purchaseOutsourceRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreatePurchaseOutsourceHandler(IBaseRepository<PurchaseOutsources> purchaseOutsourceRepository,
                                              ILogger<CreatePurchaseOutsourceHandler> logger,
                                              IMapper mapper)
        {
            _purchaseOutsourceRepository = purchaseOutsourceRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加采购/委外订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreatePurchaseOutsourceCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //判断订单编码与订单名称不能重复
                var count = await (await _purchaseOutsourceRepository.GetAll()).Where(x => x.PurchaseNumber == request.PurchaseNumber || x.PurchaseName == request.PurchaseName).CountAsync();
                if (count > 0)
                {
                    result.Msg = "订单编码或订单名称不能重复,请重新输入";
                }
                else
                {
                    //mapper转换
                    var purchase = _mapper.Map<PurchaseOutsources>(request);
                    var res = await _purchaseOutsourceRepository.Add(purchase);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "添加采购/委外订单成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加采购/委外订单异常" + ex.Message;
                _logger.LogError("添加采购/委外订单异常" + ex.Message);
            }
            return result;
        }
    }
}
